package com.yc.txx.servlet;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.yc.txx.entity.Car;
import com.yc.txx.mapper.CarMapper;
import com.yc.txx.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/QueryPageCar.s")
public class QueryPageCarServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
//        resp.setContentType("application/json;charset=utf-8");
        try(final SqlSession session = MyBatisHelper.getSession()){
            final CarMapper mapper = session.getMapper(CarMapper.class);

            final String brand = req.getParameter("brand");
            final String keyword = req.getParameter("keyword");
            // 第几页
            final String page = req.getParameter("page");
            int ipage = page == null ? 1 : Integer.parseInt(page);
            // 每页行数
            final String size = req.getParameter("size");
            int isize = size == null ? 8 : Integer.parseInt(size);

            if(ipage > 1){
                ipage ++;
            }
            // PageHelper 分页插件, 必须在查询方法前一行代码执行分页设置
            PageHelper.startPage(ipage, isize);
            final List<Car> cars = mapper.selectPage(brand, keyword);

            final String json = new Gson().toJson(cars);
            resp.getWriter().append(json);
        }
    }
}
